import React from 'react'
import {connect} from 'react-redux'
import { Modal, Form, Select, Button, Dropdown, Icon, message, Menu, Spin, Tooltip} from 'antd'
import {messages} from "share/common";
import proxiesService from 'components/template/proxies/proxies-service'
const FormItem  = Form.Item;
const Option = Select.Option;

class Stations extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible: false,
      menu: [],
      formOption: [],
      fetched: false,
      userJobsDTOList: [],
      applicationFormType: props.type,
      disabledStyle:{
        'background-color': '#F7F8FA',
        'border-color': '#CDD7EC',
        'color': '#B5C0CE',
        'cursor': 'not-allowed'
      }
    }
  }

  componentWillReceiveProps (nextProps) {
    this.setState({ applicationFormType: nextProps.type }, () => {
      this.handleGetTable()
    })
  }

  componentWillMount() {
    this.handleGetTable()
  }

  handleGetTable () {
    const { user, formType } = this.props;
    const { applicationFormType } = this.state
    let temp = [];
    user.companyWithUserJobsDTOList && user.companyWithUserJobsDTOList.map(item => {
      item.userJobsDTOList.map(it => {
        temp.push(it);
      })
    });
    this.setState({ userJobsDTOList: temp });
    !user.multiJob && proxiesService.getProxyMyForms({formType, applicationFormType}).then(res => {
      this.setState({menu: res.data});
    }).catch(e => {
      message.error(e.response.data.message);
    });
  }

  handleOK = () => {
    const { onOk, user } = this.props;
    this.props.form.validateFieldsAndScroll((err,value) => {
      if(!err){
        onOk(value.formOid, value.jobId, user.userOID);
      }
    })
  };

  handleNew = value => {
    const { onOk, user } = this.props, { userJobsDTOList } = this.state;
    onOk(value.key, userJobsDTOList[0].id, user.userOID);
  };

  handleChangeJob = key => {
    const { formType, type } = this.props;
    this.setState({ fetched: true });
    this.props.form.resetFields('formOid');
    proxiesService.getProxyMyForms({ 
      formType, 
      applicationFormType: type, 
      jobId: key 
    }).then(res => {
      this.setState({formOption: res.data, fetched: false});
    }).catch(e => {
      this.setState({ fetched: false });
      message.error(e.response.data.message);
    })
  };

  joinJob = item => {
    let res = [];
    item.position && res.push(item.position);
    item.companyName && res.push(item.companyName);
    item.departmentName && res.push(item.departmentName);
    item.duty && res.push(item.duty);
    item.rank && res.push(item.rank);
    return res.join(' - ');
  };

  handleCancel = () => {
    const { resetFields } = this.props.form;
    resetFields();
    this.setState({
      visible: false,
      formOption: []
    })
  };

  render(){
    const { visible, menu, fetched, formOption, userJobsDTOList,disabledStyle} = this.state;
    const { formType, user } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    const title = formType === '101' ? messages('components.key994')/*新建申请单*/ : (formType === '102' ? messages('components.key995')/*新建报销单*/ : messages('components.key996')/*新建借款单*/);
    console.log('<stations> menu:', menu)
    return(
      <div style={{display:'inline-block'}}>
        {
          !user.multiJob ? (
              <Dropdown 
              overlay={
              <Menu onClick={this.handleNew} style={{maxHeight:250,overflow:'auto'}}>
                {menu.map(item => {
                  return <Menu.Item key={item.formOID}>{item.formName}</Menu.Item>
                })}
              </Menu>} disabled={menu.length > 0 ? false : true}>
              {menu.length > 0 ?
                (<Button type="primary">{title}<Icon type="down" /></Button>)
                :
                (<Tooltip title="您无此类单据的申请权限，如有疑问，请联系tes@cn.mcd.com">
                  <Button type="primary" style={disabledStyle}>{title}<Icon type="down" /></Button>
                </Tooltip>)
              }
              
            </Dropdown>
            
          ) : (
            <Button type={'primary'} onClick={ () => { this.setState({ visible: true }) } }>{title}</Button>
          )
        }
        <Modal
          visible={visible}
          width={600}
          title={title}
          footer={[
            <Button key="cancel" onClick={this.handleCancel}>{messages('common.cancel')}</Button>,
            <Button key="ok" type="primary" disabled={!getFieldValue('formOid')} onClick={this.handleOK}>{messages('common.ok')}</Button>
          ]}
          onCancel={this.handleCancel}
        >
          <FormItem {...formItemLayout} label={messages('components.key992')/*岗位*/}>
            {getFieldDecorator('jobId', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/
              }]
            })(
              <Select onChange={this.handleChangeJob} style={{width: '100%'}} placeholder={messages('common.please.select')/*请选择*/}>
                {userJobsDTOList.map(item => (
                  <Option key={item.id} style={{whiteSpace: 'unset'}}>
                    {this.joinJob(item)}
                    {item.companyMainPosition && (
                      <span>（<span style={{color: "#108ee9"}}>{messages('components.key993')/*主岗*/}</span>）</span>
                    )}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
          {
            getFieldValue('jobId') && (
              <FormItem {...formItemLayout} label={messages('common.document.name')/*单据名称*/}>
                {getFieldDecorator('formOid', {
                  rules: [{
                    required: true, message: messages('common.please.select')/*请选择*/
                  }]
                })(
                  <Select style={{width: '100%'}}
                          notFoundContent={fetched ?  <Spin size="small"/> : messages('components.key410'/*无匹配结果*/)}
                          placeholder={messages('common.please.select')/*请选择*/}>
                    {
                      formOption.map(item => {
                        return <Option key={item.formOID}>{item.formName}</Option>
                      })
                    }
                  </Select>
                )}
              </FormItem>
            )
          }
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    user: state.login.loginUser
  }
}

Stations.propTypes = {
  formType: React.PropTypes.string,  //单据类型102报销单 101申请单 104借款单
  onOk: React.PropTypes.func
};

const WrappedStations = Form.create()(Stations);
export default connect(mapStateToProps)(WrappedStations);
